package com.cn.task;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import com.cn.xc.utils.DateUtil;

/**
 * FUN: 
 *
 * @author sushy
 * @date 2016-3-23 
 */
public class AtomicIntSeq extends AtomicInteger{
	
	private static final long serialVersionUID = 1876204374858662101L;
	private int maxSeq;
	private int dateOfLastGet = Integer.valueOf(DateUtil.date2Str(new Date(), "yyyyMMdd"));

	public AtomicIntSeq(int maxSeq) {
		this.maxSeq = maxSeq;
		set(1);
		dateOfLastGet = Integer.valueOf(DateUtil.date2Str(new Date(), "yyyyMMdd"));
	}

	public int getMaxSeq() {
		return maxSeq;
	}

	public void setMaxSeq(int maxSeq) {
		this.maxSeq = maxSeq;
	}

	public final int getSeq() {
		
		if(dateOfLastGet < 1){
			dateOfLastGet = Integer.valueOf(DateUtil.date2Str(new Date(), "yyyyMMdd"));
		}else{
			int curDate = Integer.valueOf(DateUtil.date2Str(new Date(), "yyyyMMdd"));
			//第二天开始的时候，重置初始值
			if( curDate > dateOfLastGet){
				set(1); 
			}
			dateOfLastGet = Integer.valueOf(DateUtil.date2Str(new Date(), "yyyyMMdd"));
		}
		
		for (;;) {
			int current = get();
			int next = current + 1;
			if (next >= maxSeq) {
				next = 0;
			}
			if (compareAndSet(current, next))
				return current;
		}
	}


}
